package cn.alusiaor.eurekaclientarticleservice.filters;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 用户信息相关的filter
 */
@Slf4j
@Component
@WebFilter(filterName = "UserFilter", urlPatterns = "/*")
public class LogFilter implements Filter {

    public static final String KEY_LOG = "X-Id";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        // 用户信息
        HttpServletRequest req = (HttpServletRequest) request;
        String userId = req.getHeader("X-Id");
        MDC.put(KEY_LOG, userId);
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(KEY_LOG);
        }
    }
}
